<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>WebSocket测试</title>
    <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1/dist/sockjs.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/stompjs@2.3.3/lib/stomp.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 0 auto;
            padding: 20px;
        }
        .message-container {
            height: 300px;
            overflow-y: auto;
            border: 1px solid #ccc;
            padding: 10px;
            margin-bottom: 10px;
        }
        .controls {
            margin-top: 20px;
        }
        button {
            padding: 8px 15px;
            margin-right: 10px;
        }
        input, textarea {
            padding: 8px;
            width: 300px;
        }
        .debug-info {
            margin-top: 20px;
            border: 1px solid #ccc;
            padding: 10px;
            background-color: #f9f9f9;
            font-family: monospace;
            font-size: 12px;
            height: 100px;
            overflow: auto;
        }
    </style>
</head>
<body>
    <h1>WebSocket聊天测试</h1>
    
    <div class="controls">
        <label>客服ID:</label>
        <input type="text" id="customerIdInput" value="cs001">
        <button id="connectBtn">连接</button>
        <button id="disconnectBtn" disabled>断开</button>
    </div>
    
    <div class="controls">
        <button id="testBtn" disabled>测试WebSocket</button>
        <button id="createSessionBtn" disabled>创建会话</button>
        <span id="sessionId"></span>
    </div>
    
    <div class="message-container" id="messageContainer"></div>
    
    <div class="controls">
        <textarea id="messageInput" placeholder="输入消息..." disabled></textarea>
        <div>
            <label>
                <input type="radio" name="modelType" value="normal" checked> 普通模型
            </label>
            <label>
                <input type="radio" name="modelType" value="think"> 思考模型
            </label>
            <label>
                <input type="radio" name="responseType" value="stream" checked> 流式
            </label>
            <label>
                <input type="radio" name="responseType" value="sync"> 同步
            </label>
        </div>
        <button id="sendBtn" disabled>发送</button>
    </div>
    
    <h3>调试信息</h3>
    <div class="debug-info" id="debugInfo"></div>
    
    <h3>Apifox参考</h3>
    <div>
        <p><strong>1. 连接WebSocket</strong></p>
        <pre>ws://localhost:8080/ws</pre>
        
        <p><strong>2. 订阅 (SUBSCRIBE)</strong></p>
        <pre>
destination: /user/cs001/queue/chat
id: sub-0</pre>
        
        <p><strong>3. 创建会话 (SEND)</strong></p>
        <pre>
destination: /app/chat.createSession
content-length: 57

{"customerId":"cs001","modelServiceName":"doubaoService"}</pre>
        
        <p><strong>4. 发送消息 (SEND)</strong></p>
        <pre>
destination: /app/chat.sendMessage
content-length: 123

{"sessionId":"SESSION_ID","customerId":"cs001","content":"你好","modelType":"normal","responseType":"stream"}</pre>
    </div>
    
    <script>
        let stompClient = null;
        let currentSessionId = null;
        let customerId = null;
        
        // DOM元素
        const connectBtn = document.getElementById('connectBtn');
        const disconnectBtn = document.getElementById('disconnectBtn');
        const testBtn = document.getElementById('testBtn');
        const createSessionBtn = document.getElementById('createSessionBtn');
        const sessionIdSpan = document.getElementById('sessionId');
        const messageInput = document.getElementById('messageInput');
        const sendBtn = document.getElementById('sendBtn');
        const messageContainer = document.getElementById('messageContainer');
        const customerIdInput = document.getElementById('customerIdInput');
        const debugInfo = document.getElementById('debugInfo');
        
        // 添加调试信息
        function addDebugInfo(message) {
            const time = new Date().toLocaleTimeString();
            debugInfo.innerHTML += `<div>[${time}] ${message}</div>`;
            debugInfo.scrollTop = debugInfo.scrollHeight;
        }
        
        // 连接WebSocket
        connectBtn.addEventListener('click', function() {
            customerId = customerIdInput.value.trim();
            if (!customerId) {
                alert('请输入客服ID');
                return;
            }
            
            addMessage('系统', '正在连接...');
            addDebugInfo('开始连接WebSocket...');
            
            // 创建SockJS连接
            const socket = new SockJS('/ws');
            stompClient = Stomp.over(socket);
            
            // 启用STOMP客户端的调试模式
            stompClient.debug = function(str) {
                console.log('STOMP: ' + str);
                addDebugInfo('STOMP: ' + str);
            };
            
            stompClient.connect({}, function(frame) {
                console.log('连接成功: ' + frame);
                addMessage('系统', '连接成功');
                addDebugInfo('连接成功: ' + frame);
                
                // 订阅个人消息
                const subscription = stompClient.subscribe('/user/' + customerId + '/queue/chat', function(message) {
                    console.log('收到消息:', message);
                    addDebugInfo('收到消息: ' + message.body);
                    
                    try {
                        const response = JSON.parse(message.body);
                        
                        if (response.type === 'SESSION_CREATED') {
                            currentSessionId = response.sessionId;
                            sessionIdSpan.textContent = '会话ID: ' + currentSessionId;
                            addMessage('系统', '会话创建成功，ID: ' + currentSessionId);
                            addMessage('机器人', response.firstMessage);
                            messageInput.disabled = false;
                            sendBtn.disabled = false;
                        } else if (response.type === 'RESPONSE_CHUNK') {
                            appendMessage('机器人', response.content);
                        } else if (response.type === 'FULL_RESPONSE') {
                            addMessage('机器人', response.content);
                        } else if (response.type === 'RESPONSE_COMPLETE') {
                            addMessage('系统', '响应完成');
                        } else if (response.type === 'ERROR') {
                            addMessage('错误', response.error);
                        } else if (response.type === 'TEST_RESPONSE') {
                            addMessage('系统', '测试响应: ' + response.message);
                        }
                    } catch (e) {
                        addMessage('错误', '解析消息失败: ' + e);
                        console.error('解析消息失败', e, message);
                        addDebugInfo('解析消息失败: ' + e);
                    }
                }, {});
                
                console.log('订阅ID:', subscription.id);
                addDebugInfo('订阅ID: ' + subscription.id);
                
                disconnectBtn.disabled = false;
                connectBtn.disabled = true;
                testBtn.disabled = false;
                createSessionBtn.disabled = false;
            }, function(error) {
                console.error('连接失败:', error);
                addMessage('错误', '连接失败: ' + error);
                addDebugInfo('连接失败: ' + error);
            });
        });
        
        // 断开连接
        disconnectBtn.addEventListener('click', function() {
            if (stompClient) {
                stompClient.disconnect();
                stompClient = null;
            }
            
            addMessage('系统', '已断开连接');
            addDebugInfo('已断开连接');
            
            disconnectBtn.disabled = true;
            connectBtn.disabled = false;
            testBtn.disabled = true;
            createSessionBtn.disabled = true;
            messageInput.disabled = true;
            sendBtn.disabled = true;
            currentSessionId = null;
            sessionIdSpan.textContent = '';
        });
        
        // 测试WebSocket
        testBtn.addEventListener('click', function() {
            if (!stompClient) {
                addMessage('错误', '未连接WebSocket');
                return;
            }
            
            addMessage('系统', '发送测试请求...');
            addDebugInfo('发送测试请求...');
            
            const testData = {
                customerId: customerId,
                timestamp: new Date().getTime()
            };
            
            const testDataJson = JSON.stringify(testData);
            addDebugInfo('测试数据: ' + testDataJson);
            
            stompClient.send('/app/chat.test', {}, testDataJson);
        });
        
        // 创建会话
        createSessionBtn.addEventListener('click', function() {
            if (!stompClient) {
                addMessage('错误', '未连接WebSocket');
                return;
            }
            
            addMessage('系统', '正在创建会话...');
            addDebugInfo('发送创建会话请求');
            
            const sessionData = {
                customerId: customerId,
                modelServiceName: 'doubaoService'
            };
            
            const sessionDataJson = JSON.stringify(sessionData);
            addDebugInfo('会话数据: ' + sessionDataJson);
            
            stompClient.send('/app/chat.createSession', {
                'content-type': 'application/json'
            }, sessionDataJson);
        });
        
        // 发送消息
        sendBtn.addEventListener('click', function() {
            if (!stompClient || !currentSessionId) {
                addMessage('错误', '未连接或未创建会话');
                return;
            }
            
            const content = messageInput.value.trim();
            if (!content) {
                alert('请输入消息内容');
                return;
            }
            
            const modelType = document.querySelector('input[name="modelType"]:checked').value;
            const responseType = document.querySelector('input[name="responseType"]:checked').value;
            
            const messageData = {
                sessionId: currentSessionId,
                customerId: customerId,
                content: content,
                modelType: modelType,
                responseType: responseType
            };
            
            const messageDataJson = JSON.stringify(messageData);
            addDebugInfo('发送消息: ' + messageDataJson);
            
            stompClient.send('/app/chat.sendMessage', {
                'content-type': 'application/json'
            }, messageDataJson);
            
            addMessage('客服', content);
            messageInput.value = '';
        });
        
        // 添加消息到消息容器
        function addMessage(sender, content) {
            const messageElement = document.createElement('div');
            messageElement.innerHTML = `<strong>${sender}:</strong> ${content}`;
            messageContainer.appendChild(messageElement);
            messageContainer.scrollTop = messageContainer.scrollHeight;
        }
        
        // 追加消息内容（用于流式响应）
        let lastMessageElement = null;
        function appendMessage(sender, content) {
            if (!lastMessageElement || !lastMessageElement.querySelector('strong').textContent.includes(sender)) {
                lastMessageElement = document.createElement('div');
                lastMessageElement.innerHTML = `<strong>${sender}:</strong> <span>${content}</span>`;
                messageContainer.appendChild(lastMessageElement);
            } else {
                const contentSpan = lastMessageElement.querySelector('span');
                contentSpan.textContent += content;
            }
            messageContainer.scrollTop = messageContainer.scrollHeight;
        }
    </script>
</body>
</html> 